package com.leyou.sms.mq;

import com.leyou.common.utils.JsonUtils;
import com.leyou.sms.config.SmsProperties;
import com.leyou.sms.utils.SendSmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

import static com.leyou.common.constants.MQConstants.Exchange.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.Queue.SMS_VERIFY_CODE_QUEUE;
import static com.leyou.common.constants.MQConstants.RoutingKey.VERIFY_CODE_KEY;


/**
 * @author xiuer
 * @description
 * @create 2019/7/6 16:34
 */
@Slf4j
@Component
public class SmsListener {
    @Autowired
    private SmsProperties prop;
    @Autowired
    private SendSmsUtils sendSmsUtils;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = SMS_VERIFY_CODE_QUEUE),
            exchange = @Exchange(
                    value = SMS_EXCHANGE_NAME,
                    type = ExchangeTypes.TOPIC
            ),
            key = VERIFY_CODE_KEY))
    public void listenVerifyCode(Map<String, String> msg) {
        if (msg == null) {
            return;
        }
        //移除手机号码数据，返回的是手机号码  只剩下短信的参数
        String phone = msg.remove("phone");
        if (StringUtils.isBlank(phone)) {
            return;
        }
        try {
            String param = JsonUtils.toString(msg);
            sendSmsUtils.sendMessage(phone, prop.getSignName(), prop.getVerifyCodeTemplate(), param);
        } catch (Exception e) {
            //短信验证码发送失败，不重发，捕获该异常
            log.error("【短信微服务】短信验证码发送失败", e.getMessage(), e);
        }
    }
}


